import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import storage from '../../shared/storage';
import {HomeService} from "../home.service";
import { Router, ActivatedRoute, NavigationEnd , ParamMap } from '@angular/router';
import {NzMessageService, NzModalService} from 'ng-zorro-antd';
import SysData from '../../shared/sysData';
import { TranslateService } from '@ngx-translate/core';
import Mysocket from '../../shared/mySocket';
declare var $: any;
@Component({
  selector: 'app-device-debug-am',
  templateUrl: './device-debug-am.component.html',
  styleUrls: ['./device-debug-am.component.scss']
})
export class DeviceDebugAmComponent implements OnInit {
    @Output() close: EventEmitter<boolean> = new EventEmitter<boolean>();
    @Output() offLine: EventEmitter<boolean> = new EventEmitter<boolean>();
    movefrequently=storage.getSessionStorage('movefrequently');//频率：50 || 60
  xtotal=0;
  isSpinning:boolean=false;
  waveDataXList=[];//波形图X轴
  waveDataYList=[]; //波形图Y轴
  formatOne = percent =>"";
  sameAnt;
  selectedMode;
  selectedAntenna;
  state=false;  //默认停止
  isAMmainShow:boolean=false;//主天线是否亮灯
  isAMsubsidiaryShow:boolean=false;//副天线是否亮灯
  isModeChangeShow:boolean=false;
  previousKeyVal={};//初始的天线，key，value集合
  currentKeyVal={}; //现在的天线，key，value集合
  signalwaveList=[];//信号波形
  signalItem={};//信号幅值
  antenEleItem={};//天线电流
  alarmTestItem={};//报警测试
  readParamItem={};//读取参数
  restoreFactoryItem={};//恢复出厂设置
  signalWaveOption={};//信号波形内容;折线图
//   signalWaveOption2={};//信号波形内容;柱状图
  sameMoveList=[];//同步相移
  workModeItem={};//工作模式
  currentAnten;//当前天线
  waveOption1=[];//停止选项
  waveOption2=[]; //三个天线选项
  //moduleCode
  AMcommand:any=storage.getSessionStorage("AA10_EAS_AM_CMD");   //AM通用调试命令
  AMmainList:any=storage.getSessionStorage("AA10_EAS_AM_MAIN_FUNCTION_CMD");   //AM主天线性能配置
  AMsubsidiaryList:any=storage.getSessionStorage("AA10_EAS_AM_SECOND_FUNCTION_CMD"); //AM副天线性能配置
  AMalarmList:any=storage.getSessionStorage("AA10_EAS_AM_ALARM_CMD"); //AM报警设置  颜色板块
  elecList:any=storage.getSessionStorage("AA10_EAS_DEBUG_PARAM_ELEC");//天线电流
  signalList:any=storage.getSessionStorage("AA10_EAS_AM_MAIN_SIGNAL_CMD");//信号幅值(主)
  signalSecondList:any=storage.getSessionStorage("AA10_EAS_AM_SECOND_SIGNAL_CMD");//信号幅值(副)
  otherCMDList:any=storage.getSessionStorage("AA10_EAS_AM_OTHER_CMD");  //其它设置
  //选择项
  waveOptionList:any=storage.getSessionStorage("AA10_EAS_DEBUG_PARAM_AM_WAVE"); //AM波形图参数
  AMtype:any=storage.getSessionStorage("AA10_EAS_AM_TYPE");   //AM天线类型,主天线OR副天线
  workModeList:any=storage.getSessionStorage("AA10_EAS_DEBUG_PARAM_MODE");  //工作模式
  frequencyList:any=storage.getSessionStorage("AA10_EAS_DEBUG_PARAM_FREQUENCY");//频率范围
  launchDirList:any=storage.getSessionStorage("AA10_EAS_DEBUG_PARAM_LAUNCHDIR");//发射开关
  lightColorList:any=storage.getSessionStorage("AA10_EAS_DEBUG_PARAM_LIGHTCOLOR");//常亮颜色
  alermColorList:any=storage.getSessionStorage("AA10_EAS_DEBUG_PARAM_ALARMCOLOR");// 报警颜色
  alermRateList:any=storage.getSessionStorage("AA10_EAS_DEBUG_PARAM_ALARMRATE");// 报警速率
  alarmLightTimeList:any=storage.getSessionStorage("AA10_EAS_DEBUG_PARAM_ALARMLIGHTTIME");//报警灯时间
  receiveTime:any=storage.getSessionStorage("AA10_EAS_DEBUG_PARAM_RECEIVETIME");//接收时间
  wireFlipList:any=storage.getSessionStorage("AA10_EAS_DEBUG_PARAM_WIREFLIP");//火零翻转
  LoginForm:any=storage.getSessionStorage('LoginForm');
  //本次操作sessionid
  sessionId= "";
  constructor(
    private router: Router,
    private homeService:HomeService,
    private message:NzMessageService,
    private modalService: NzModalService,
    private translateService:TranslateService) { }
    ngOnInit() {
        console.log(this.receiveTime);
        this.currentKeyVal['key4b']=0; //同步相移，默认为0;
        this.currentKeyVal['key60']=this.receiveTime[0].value; //接收时间默认为第一个
        this.waveOption1=this.waveOptionList.splice(3,1); //停止  (value:3)
        this.waveOption2=this.waveOptionList.splice(0,3);  //天线1，天线2，天线3(value:0,1,2)
        this.currentAnten=this.waveOption1[0].value;  //默认为停止
        this.workModeItem=this.workModeList[0]; //工作模式，默认为第0个
        this.selectedAntenna=this.AMtype[0].value;
        //主天线性能
        this.AMmainList.forEach(item=>{
        if(item.key==40){
            item['min']=1;
            item['max']=7;
            this.currentKeyVal['key'+item.key]=1;
        } else if(item.key==41){
            item['min']=0;
            item['max']=250;
            this.currentKeyVal['key'+item.key]=0;
        } else if(item.key==42){
            item['min']=3;
            item['max']=15;
            this.currentKeyVal['key'+item.key]=3;
        } else if(item.key==43){
            this.currentKeyVal['key'+item.key]=this.frequencyList[0].value;
        } else if(item.key==44){
            item['min']=0;
            item['max']=99;
            this.currentKeyVal['key'+item.key]=0;
        } else if(item.key==45){
            item['min']=0;
            item['max']=50;
            this.currentKeyVal['key'+item.key]=0;
        } else if(item.key==46){
            this.currentKeyVal['key'+item.key]=this.launchDirList[0].value;
        } else if(item.key==48){
            item['min']=1;
            item['max']=99;
            this.currentKeyVal['key'+item.key]=1;
        }
        });
        //副天线性能
        this.AMsubsidiaryList.forEach(item=>{
        if(item.key==50){
            item['min']=1;
            item['max']=7;
            this.currentKeyVal['key'+item.key]=1;
        } else if(item.key==51){
            item['min']=0;
            item['max']=250;
            this.currentKeyVal['key'+item.key]=0;
        } else if(item.key==52){
            item['min']=3;
            item['max']=15;
            this.currentKeyVal['key'+item.key]=3;
        } else if(item.key==53){
            this.currentKeyVal['key'+item.key]=this.frequencyList[0].value;
        } else if(item.key==54){
            item['min']=0;
            item['max']=99;
            this.currentKeyVal['key'+item.key]=0;
        } else if(item.key==55){
            item['min']=0;
            item['max']=50;
            this.currentKeyVal['key'+item.key]=0;
        } else if(item.key==56){
            this.currentKeyVal['key'+item.key]=this.launchDirList[0].value;
        } else if(item.key==58){
            item['min']=1;
            item['max']=99;
            this.currentKeyVal['key'+item.key]=1;
        }
        });
        //电流初始化
        this.elecList.forEach(item=>{
        this.currentKeyVal['key'+item.key]=0;
        });
        //主信号幅值
        this.signalList.forEach(item=>{
        this.currentKeyVal['key'+item.key]=0;
        });
        //副信号幅值
        this.signalSecondList.forEach(item=>{
        this.currentKeyVal['key'+item.key]=0;
        });
        //报警测试
        this.alarmTestItem=this.AMcommand.find(item=>{
        return item.key=='4e';
        });
        //同步相移
        this.AMcommand.forEach(item=>{
        if(item.key=='4b'){
            if(this.movefrequently){
                item['min']=0;
                item['max']=this.movefrequently=='50'?20.0:16.7;
                this.sameMoveList.push(item);
                this.currentKeyVal['key'+item.key]=0;
            }
        } else
        if(item.key=='4d'){
            //信号波形
            this.signalwaveList.push(item);
            this.currentKeyVal['key'+item.key]=this.waveOption1[0].value;
        } else if(item.key==49){
            //工作模式
            this.workModeItem=this.workModeList[0];
            this.currentKeyVal['key'+item.key]=this.workModeList[0].value;
        }
        });
        //信号幅度
        this.signalItem=this.AMcommand.find(item=>{
        return item.key=='bb';
        });
        //天线电流
        this.antenEleItem=this.AMcommand.find(item=>{
        return item.key=='dd';
        });
        //恢复出厂
        this.restoreFactoryItem=this.AMcommand.find(item=>{
        return item.key=='4f';
        });
        //报警设置
        this.AMalarmList.forEach(item=>{
        if(item.key=='4c'){
            this.currentKeyVal['key'+item.key]=this.alermColorList[0].value;
        } else if(item.key=='5b'){
            this.currentKeyVal['key'+item.key]=this.lightColorList[0].value;
        } else if(item.key=='5a'){
            this.currentKeyVal['key'+item.key]=this.alarmLightTimeList[0].value;
        } else if(item.key=='59'){
            this.currentKeyVal['key'+item.key]=this.alermRateList[0].value;
        }
        });
        //其它设置
        this.otherCMDList.forEach(item=>{
        if(item.key=='60'){
            this.currentKeyVal['key'+item.key]=this.receiveTime[0].value;
        } else if(item.key=='4a'){
            this.currentKeyVal['key'+item.key]=this.wireFlipList[0].value;
        }
        });
        this.currentKeyVal['key5e']="1.0.0";
        Mysocket.oncloseWS();
        setTimeout(()=>{
            Mysocket.createSocket();
            this.initSocketMsg();
            this.chgAntType();
        },500);
    }
    ngOnDestroy(): void {
        Mysocket.oncloseWS();
    }
    //切换主副天线
    changeAmType(AMtype){
        if(this.selectedAntenna!==AMtype){
            this.selectedAntenna=AMtype;
            this.chgAntType();
        }
    }
    //主副天线切换时
    AmTypeChange(){
        this.chgAntType();
    }
    //选择工作模式时；
    chooseWorkMode(item){
        this.selectedMode=item.key;
    }
    //切换工作模式
    switchMode(){
        if(this.state) return;
        this.selectedMode=this.workModeList.find(item=>{
        return item.key==this.workModeItem['key'];
        }).key;
        this.isModeChangeShow=true;
    }
    //取消工作模式选择；
    cancel(){
        this.selectedMode="";
        this.isModeChangeShow=false;
    }
    //保存工作模式
  saveMode(){
    //提示是否切换
    this.modalService.confirm({
      nzTitle     : this.translateService.instant('tip'),
      nzContent   : `<b>`+this.translateService.instant('eas_note_change_mode')+`</b>`,
      nzOkText    : this.translateService.instant('OK'),
      nzOkType    : 'primary',
      nzOnOk      : () => {
        this.isModeChangeShow=false;
        setTimeout(()=>{
          if(this.selectedMode=='2' || this.selectedMode=='4'){
            this.selectedAntenna=this.AMtype[1].value;
          } else if(this.selectedMode=='1' || this.selectedMode=='3'){
            this.selectedAntenna=this.AMtype[0].value;
          } else {
            this.selectedAntenna=this.AMtype.find(item=>{
              return item.value==this.selectedAntenna;
            }).value;
          }
          this.workModeItem=this.workModeList.find(item=>{
            return item.key==this.selectedMode;
          });
          this.currentKeyVal['key49']=this.workModeItem['value'];
          this.sendAntConfigOrder('49',this.workModeItem['value']);
        },100);
      },
      nzCancelText: this.translateService.instant('cancel'),
      nzOnCancel  : () => {
      }
    });
  }
  exit(){
    this.close.emit(true);
  }
    //读取参数
    readParam(){
        this.chgAntType();
    }
  //恢复出厂设置
  restoreFactory(){
    this.modalService.confirm({
      nzTitle     : this.translateService.instant('tip'),
      nzContent   : `<b>`+this.translateService.instant('eas_note_restore')+`</b>`,
      nzOkText    : this.translateService.instant('OK'),
      nzOkType    : 'primary',
      nzOnOk      : () => {
        //如果波形图运行，先停止
        if(this.state){
          this.state=false;
          this.stateChange();
        }
        this.sendAntConfigOrder('4f',0);
      },
      nzCancelText: this.translateService.instant('cancel'),
      nzOnCancel  : () => {
      }
    });
  }
  //状态改变，运行或者停止
  stateChange(){
    let curVal;
    if(this.state){
      this.currentKeyVal['key4d']=this.waveOption2[0].value;
      curVal=this.waveOption2[0].value;
      this.chgWaveform(0);
    } else {
        this.currentKeyVal['key4d']=this.waveOption1[0].value;
        curVal=this.waveOption1[0].value;
        this.chgWaveform(3);
    }
  }
  //选择天线后；
  stateChange2(code,e){
    this.state=true;
    this.showWave();
    this.chgWaveform(e);
  }
    //波形图启/停
    chgWaveform(val){
        let data={
            LoginForm:this.LoginForm,
            DeviceMessage:{val}
        }
        this.homeService.chgWaveform(data).subscribe(res=>{
            if(res.status=1){
                this.message.success(this.translateService.instant('successfully'));
            }else {

            }
        });
    }
  //主副天线切换
    chgAntType(){
        let  data={LoginForm:this.LoginForm};
        this.homeService.chgAntType(data).subscribe(res=>{
            if(res.status=1){
                this.message.success(this.translateService.instant('successfully'));
            }else {
                this.message.error(res.message);
            }
        });
    }
    //接收信息
    initSocketMsg(){
        let _this=this;
        window.addEventListener("onmessageWS",function(e){
            let Msg=(JSON.parse(e['detail']['data']['data']));
            console.log(Msg);
            switch(Msg.moduleCode){
                //主天线性能；
                case '40':
                case '41':
                case '42':
                case '43':
                case '44':
                case '45':
                case '46':
                case '48':
                //副天线性能；
                case '50':
                case '51':
                case '52':
                case '53':
                case '54':
                case '55':
                case '56':
                case '58':
                //信号幅值
                case 'b1':
                case 'b2':
                case 'b3':
                case 'b4':
                //报警设置
                case '4c':
                case '5b':
                case '5a':
                case '59':
                //其它设置
                case '4a':
                    _this.currentKeyVal['key'+Msg.moduleCode]=Msg.val;
                    _this.previousKeyVal['key'+Msg.moduleCode]=Msg.val;
                    break;
                case '5f':
                    _this.movefrequently=Msg.val;
                    _this.AMcommand.forEach(item=>{
                        if(item.key=='4b'){
                            item['min']=0;
                            item['max']=Msg.val==50?20.0:16.7;
                            _this.sameMoveList.push(item);
                            _this.currentKeyVal['key'+item.key]=_this.currentKeyVal['key'+item.key] || 0;
                        }
                    });
                    storage.setSessionStorage('movefrequently',Msg.val);
                    break;
                //同步相移
                case '4b':
                //接收时间
                case '60':
                    _this.currentKeyVal['key'+Msg.moduleCode]=Msg.val;
                    _this.previousKeyVal['key'+Msg.moduleCode]=Msg.val;
                    if(_this.xtotal!==0){
                        _this.calcPosition();
                    }
                    break;
                //天线电流
                case 'dd':
                    let valArr=Msg.val.split(",");
                    _this.currentKeyVal['key0']=_this.previousKeyVal['key0']=valArr[0];
                    _this.currentKeyVal['key1']=_this.previousKeyVal['key1']=valArr[1];
                    _this.currentKeyVal['key2']=_this.previousKeyVal['key2']=valArr[2];
                    _this.currentKeyVal['key3']=_this.previousKeyVal['key3']=valArr[3];
                    break;
                // 工作模式：
                case '49':
                    _this.workModeItem=_this.workModeList.find(item=>{
                    return item.value==Msg.val;
                    });
                    _this.currentKeyVal['key'+Msg.moduleCode]=Msg.val;
                    _this.previousKeyVal['key'+Msg.moduleCode]=Msg.val;
                    if(Msg.val==2 || Msg.val==4){
                        _this.selectedAntenna=_this.AMtype[1].value;
                    } else if(Msg.val==1 || Msg.val==3){
                        _this.selectedAntenna=_this.AMtype[0].value;
                    } else {
                        _this.selectedAntenna=_this.AMtype.find(item=>{
                        return item.value==_this.selectedAntenna;
                    }).value;
                    }
                    break;
                //信号波形
                case '4d':
                    //运行时，接收的数据有效，停止时，接收的数据不展示
                    if(_this.state){
                        _this.xtotal=Msg.xtotal;
                        _this.dealWaveMsg(Msg.pc,Msg.val);
                       _this.calcPosition();
                    }
                    break;
                //硬件版本
                case '5e':
                    _this.currentKeyVal['key'+Msg.moduleCode]=Msg.val;
                    break;
                case 'a1':
                    _this.isAMmainShow=Msg.val==161?true:false;
                    setTimeout(()=>{
                        _this.isAMmainShow=false;
                    },10000);
                    break;
                case 'a2':
                    _this.isAMsubsidiaryShow=Msg.val==162?true:false;
                    setTimeout(()=>{
                        _this.isAMsubsidiaryShow=false;
                    },10000);
                    break;
                case 'close':
                    Mysocket.oncloseWS();
                    _this.offLine.emit(true);
                    break;
                default:
                    break;
            }
    });
  }
  //处理波形图
  wavePcXValMap={};
  wavePcYValMap={};
  dealWaveMsg(pc,val){
    let xVal = JSON.parse(val)['x'];
    let yVal = JSON.parse(val)['y'];
    this.wavePcXValMap[pc] = xVal;
    this.wavePcYValMap[pc] = yVal;
    let concatXArr = [];
    let concatYArr = [];
    for(let key in this.wavePcXValMap){
      let xArr = this.wavePcXValMap[key];
      let yArr = this.wavePcYValMap[key];
      concatXArr = concatXArr.concat(xArr);
      concatYArr = concatYArr.concat(yArr);
    }
    this.waveDataXList = concatXArr;
    this.waveDataYList = concatYArr;
    this.showWave();
  }
  //展示折线图
  showWave(){
    this.signalWaveOption={
      grid:{
          x:'30px',   //左侧与y轴的距离
          x2:'30px',   //右侧与y轴的距离
          y:'20px',
          y2:'20px'
      },
      color:["#FF0000","#00CC00"],
      xAxis : [
          {
              type : 'category',//类目
              data : this.waveDataXList,
              boundaryGap: true,
              interval:1000,
              axisLabel:{
                //X轴刻度配置
                min:0,
                max:20000,
                formatter: function(value, index) {
                   return Math.round(value/100)*100;
                }
              }
          }
      ],
      yAxis: [
          {
            type: 'value',
            max : 250,
            min : 0,
            splitNumber : 6
          },
          {
            type: 'value',
          },
      ],
      series:{
        symbol: "none",
        name:'W1',
        type:'line',
        color: this.currentKeyVal['key4d']==this.waveOption2[0].value?'#074eb1':(this.currentKeyVal['key4d']==this.waveOption2[1].value?'#800080':'#00ffff'),
        data:this.waveDataYList,
        areaStyle: {
          color:this.currentKeyVal['key4d']==this.waveOption2[0].value?'#074eb1':(this.currentKeyVal['key4d']==this.waveOption2[1].value?'#800080':'#00ffff'),
        },
        splitLine:{
          show:false
        }
      }
    };
  }
 //接收时间变化时；
  receiveTimeChange(code,e){
    this.sendAntConfigOrder(code,e);
    if(this.xtotal!==0){
        this.calcPosition();
    }
  }
    //同步相移变化时；
    sameMoveChange(){
            if(this.movefrequently=='50'){
                if(this.currentKeyVal['key4b'].toString().includes('.')){
                    this.currentKeyVal['key4b']=Number(Math.round(this.currentKeyVal['key4b']*10)/10);
                }
            }else if(this.movefrequently=='60'){
                console.log(Math.round(this.currentKeyVal['key4b']/0.0835));
                this.currentKeyVal['key4b']=Number((Math.round(this.currentKeyVal['key4b']/0.0835)*0.0835).toString().substr(0,6));
                console.log(this.currentKeyVal['key4b']);
            }
            if(this.xtotal!==0){
                this.calcPosition();
            }
    }
   //同步相移，保存数据的变化；
    saveMove(code){
        console.log(code);
        let curVal=Number(this.currentKeyVal['key'+code]);
        console.log(curVal);
        this.sendAntConfigOrder(code,curVal);
    }
   //命令下发
   sendAntConfigOrder(code,e){
        let data={
            LoginForm:storage.getSessionStorage('LoginForm'),
            DeviceMessage:{
                moduleCode:code,
                val:e,
            }
        };
        this.homeService.order(data).subscribe(res=>{
            if(res.status==1){
                this.message.success(this.translateService.instant('eas_order_success'));
            }else {
                this.message.error(res.message);
            }
        });
    }
    //报警测试
    testAlarm(){
        this.sendAntConfigOrder('4e',0);
    }
    //计算位置
  calcPosition(){
    if(this.xtotal==0){
      return;
    }
    if($(".barItemOver")){
      $(".barItemOver").remove();
    }
    let num1=1300;
    let gap1=300;
    let num2=this.currentKeyVal['key60']==0?2000:1000;
    let wE=$(".echart2").width() -1; //总长度
    let w1=num1*wE/this.xtotal;  //第0/二/四个的长度
    let w2=num2*wE/this.xtotal;  //第一/三/五个的长度
    $(".barItem0,.barItem2,.barItem4").css({'width':w1});
    $(".barItem1,.barItem3,.barItem5").css({'width':w2});
    this.calcPosition2('.barItem0',0,num1,w1,this.xtotal);
    this.calcPosition2('.barItem1',(num1+gap1),(num1+gap1+num2),w1,this.xtotal);
    this.calcPosition2('.barItem2',this.xtotal/3,this.xtotal/3+num1,w1,this.xtotal);
    this.calcPosition2('.barItem3',(this.xtotal/3+num1+gap1),(this.xtotal/3+num1+gap1+num2),w1,this.xtotal);
    this.calcPosition2('.barItem4',this.xtotal/3*2,this.xtotal/3*2+num1,w1,this.xtotal);
    this.calcPosition2('.barItem5',(this.xtotal/3*2+num1+gap1),(this.xtotal/3*2+num1+gap1+num2),w1,this.xtotal);
  }
  calcPosition2(barItem,numFirst,numSecond,w1,xtotal){
    let wE=$(".echart2").width() -1; //总长度
    let xDistance=(xtotal/3)/200*this.currentKeyVal['key4b'];
    //第二个位置小于最大值
    if(numSecond + xDistance <=xtotal){
      $(barItem).css({left:(xDistance+numFirst)*wE/xtotal+'px'});
    } else {
      //第二个位置大于最大值，第一个位置小于最大值；
      if(numFirst+xDistance < xtotal){
        let overWid=(numSecond+xDistance-xtotal)*wE/xtotal;
        $(barItem).css({left:(xDistance+numFirst)*wE/xtotal+'px'});
        let overDiv=$("<div class='barItemOver'></div>");
        $(".echart2").append(overDiv);
        $(".barItemOver").css({'position':'absolute',top: '40px',bottom: '18px','border-bottom':'0px','width':overWid+'px',left:0,borderTopWidth:'1px',borderTopStyle:'solid',borderTopColor:$(barItem).css('border-right-color'),borderRightColor:$(barItem).css('border-right-color'),borderRightWidth:'1px',borderRightStyle:'solid'});
      } else if(numFirst+xDistance >= xtotal){
        //第一个位置大于最小值
        $(barItem).css({left:(xDistance+numFirst - xtotal)*wE/xtotal+'px'});
      }
    }
  }
}

